<?php

namespace App\Repository;

use App\Consts\GlobalConst;
use App\Consts\GlobalCounterConst;
use App\Consts\GlobalDynamicConst;
use App\Consts\GlobalNoteConst;
use App\Models\Cache\Cache;
use App\Models\Cache\CacheKey;
use App\Models\IndexDynamic;
use App\Models\SysDynamic;
use App\Models\UserAttention;
use Illuminate\Database\Eloquent\Builder;

class DynamicRepository extends BaseRepository
{
    /**
     * @param $searchParams
     * @return Builder
     */
    public function getAttentionDynamicList($searchParams)
    {
        $provider = UserAttention::getInstance($searchParams['current_user_id'])
            ->where('user_attention_id', $searchParams['current_user_id'])
            ->where('is_deleted', GlobalConst::IS_NOT_DELETE)
            ->where('is_view', GlobalDynamicConst::IS_VIEW)
            ->whereIn('dynamic_type', [GlobalDynamicConst::DYNAMIC_TYPE_ORIGINAL_ARTICLE, GlobalDynamicConst::DYNAMIC_TYPE_NOTE, GlobalDynamicConst::DYNAMIC_TYPE_USER_RECOMMEND_ARTICLE])
            ->whereIn('note_type', [GlobalNoteConst::TYPE_ARTICLE_NOTE, GlobalNoteConst::TYPE_LINE_NOTE]);

        if (!empty($searchParams['last_id'])) {
            $model = UserAttention::getInstance($searchParams['current_user_id'])
                ->where('target_id', $searchParams['last_id'])
                ->where('user_attention_id', $searchParams['current_user_id'])
                ->first();
            if ($model) {
                $provider->where('apply_at', '<', $model->apply_at);
            }
        }

        $provider->orderByDesc('apply_at');

        return $this->setPagination($provider);
    }

    /**
     * @param $searchParams
     * @return Builder
     */
    public function getUserDynamicList($searchParams)
    {
        $provider = SysDynamic::getInstance($searchParams['user_id'])
            ->where('user_id', $searchParams['user_id'])
            ->where('is_deleted', GlobalConst::IS_NOT_DELETE)
            ->whereIn('is_view', (array)$searchParams['is_view']);

        if (!array_key_exists('is_allow_essay_note', $searchParams)) {
            $provider->whereIn('note_type', [GlobalNoteConst::TYPE_ARTICLE_NOTE, GlobalNoteConst::TYPE_LINE_NOTE]);
        }

        if (!array_key_exists('is_allow_topic', $searchParams)) {
            $provider->whereIn('target_type', [GlobalConst::TARGET_TYPE_ARTICLE, GlobalConst::TARGET_TYPE_NOTE]);
        }

        if (!empty($searchParams['last_id'])) {
            if ($model = SysDynamic::getInstance($searchParams['user_id'])->where('dynamic_id', $searchParams['last_id'])->first()) {
                $provider->where('created_at', '<', $model->created_at);
            }
        }

        $provider->orderByDesc('created_at');

        return $this->setPagination($provider);
    }

    /**
     * @param $loadData
     * @return SysDynamic|bool|\Illuminate\Database\Eloquent\Model
     */
    public function addDynamic($loadData)
    {
        $dynamic = SysDynamic::getModel($loadData['user_id'])
            ->where('user_id', $loadData['user_id'])
            ->where('target_id', $loadData['target_id'])
            ->where('type', $loadData['type'])
            ->first();
        if ($dynamic) {
            $dynamic->created_at = time();
            $dynamic->updated_at = time();
            $dynamic->is_deleted = GlobalConst::IS_NOT_DELETE;
            $dynamic->is_view = GlobalDynamicConst::IS_VIEW;
            $dynamic->save();
            $indexDynamic = IndexDynamic::getModel()
                ->where('user_id', $loadData['user_id'])
                ->where('target_id', $loadData['target_id'])
                ->first();
            if ($indexDynamic) {
                $indexDynamic->created_at = time();
                $indexDynamic->updated_at = time();
                $indexDynamic->is_deleted = GlobalConst::IS_NOT_DELETE;
                $indexDynamic->is_view = GlobalDynamicConst::IS_VIEW;
                $indexDynamic->save();
            }
            return $dynamic;
        }

        $dynamic = SysDynamic::getModel($loadData['user_id'])->create($loadData);
        $indexDynamic = IndexDynamic::getModel()->create($loadData);

        // 更新用户计数缓存
        Cache::getInstance([
            'user_id' => $dynamic->user_id,
        ])->incrFromArray(CacheKey::COUNTER_USER, GlobalCounterConst::COUNT_DYNAMIC);

        return $dynamic && $indexDynamic ? $dynamic : false;
    }

    public function getDynamicsByIdArr($dynamicIdArr)
    {
        return IndexDynamic::getInstance()
            ->whereIn('dynamic_id', (array)$dynamicIdArr)
            ->get();
    }

    public function getDynamicByUserId($dynamicId, $userId)
    {
        return SysDynamic::getInstance($userId)
            ->where('user_id', $userId)
            ->where('dynamic_id', $dynamicId)
            ->first();
    }

    /**
     * @param $id
     * @return mixed
     */
    public function getDynamicById($id)
    {
        $index = IndexDynamic::getInstance()->find($id);
        if (empty($index)) return [];
        return SysDynamic::getInstance($index->user_id)
            ->where('dynamic_id', $id)
            ->first();
    }

    /**
     * @param $id
     * @param $userId
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null|array
     */

    /**
     * @param $dynamicId
     * @return Builder|\Illuminate\Database\Eloquent\Model|object|null|SysDynamic
     */
    public function getDynamic($dynamicId)
    {
        $userId = IndexDynamic::getInstance()
            ->select(['user_id'])
            ->where('dynamic_id', $dynamicId)
            ->value('user_id');

        return SysDynamic::getRelationInstance($userId)
            ->where('dynamic_id', $dynamicId)
            ->first();
    }

    /**
     * @param SysDynamic $dynamic
     * @return mixed
     */
    public function delDynamic($dynamic)
    {
        $dynamic->index->updateFormat(['is_deleted' => GlobalConst::IS_DELETED]);

        return $dynamic->updateFormat(['is_deleted' => GlobalConst::IS_DELETED]);
    }

    /**
     * @param SysDynamic $dynamic
     * @return SysDynamic
     */
    public function delDynamicBySelf(SysDynamic $dynamic)
    {
        IndexDynamic::getModel()
            ->where('dynamic_id', $dynamic->dynamic_id)
            ->update(['is_deleted' => GlobalConst::IS_DELETED]);

        $dynamic->update(['is_deleted' => GlobalConst::IS_DELETED]);
        return $dynamic;
    }

    /**
     * 通过targetId删除动态
     * @param $targetId
     * @return array|bool|SysDynamic|null
     */
    public function delDynamicByTargetId($targetId)
    {
        $dynamic = null;
        $indexDynamic = IndexDynamic::getModel()
            ->where('target_id', $targetId)
            ->first();
        if (!$indexDynamic) {
            return false;
        }

        $dynamic = $this->getDynamicById($indexDynamic->dynamic_id);
        if (!$dynamic) {
            return false;
        }

        $indexDynamic->update(['is_deleted' => GlobalConst::IS_DELETED, 'is_view' => GlobalDynamicConst::IS_NOT_VIEW]);
        $dynamic->update(['is_deleted' => GlobalConst::IS_DELETED, 'is_view' => GlobalDynamicConst::IS_NOT_VIEW]);

        return $dynamic;
    }
}
